package com.example.servlet;

import com.example.DAO.DBUtilsDAO;
import com.example.DAO.impl.DBUtilsFactory;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Random;

@WebServlet({"/addProducts"})
public class AddProductsServlet extends HttpServlet {
    private DBUtilsDAO dbConnection = DBUtilsFactory.getDBConnection();

    public AddProductsServlet() {
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Random rand = new Random();
        int productId = rand.nextInt(90) + 10;
        String wineName = req.getParameter("wineName");
        int price = Integer.parseInt(req.getParameter("price"));
        int product_inventory = Integer.parseInt(req.getParameter("product_inventory"));
        String status = req.getParameter("status");
        String sqlSelect = "SELECT COUNT(*) FROM products WHERE wine_name = ?";
        boolean productExists = false;

        try (Connection conn = this.dbConnection.getConnection();
             PreparedStatement prepSelect = conn.prepareStatement(sqlSelect)) {

            prepSelect.setString(1, wineName);
            ResultSet rs = prepSelect.executeQuery();
            if (rs.next()) {
                int count = rs.getInt(1);
                productExists = count > 0;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        if (productExists) {
            req.setAttribute("warnMeg", "商品已经存在,请重新添加");
            req.getRequestDispatcher("/AddProducts.jsp").forward(req, resp);
        } else {
            String sqlInsert = "INSERT INTO products (product_id, wine_name, price, product_inventory, status) VALUES (?, ?, ?, ?, ?)";
            try (Connection conn = this.dbConnection.getConnection();
                 PreparedStatement prepInsert = conn.prepareStatement(sqlInsert)) {

                prepInsert.setInt(1, productId);
                prepInsert.setString(2, wineName);
                prepInsert.setInt(3, price);
                prepInsert.setInt(4, product_inventory);
                prepInsert.setString(5, status);

                int affectedRows = prepInsert.executeUpdate();
                if (affectedRows > 0) {
                    resp.sendRedirect("Products.jsp");
                } else {
                    req.setAttribute("product_warn", wineName + "添加失败");
                    req.getRequestDispatcher("/AddProducts.jsp").forward(req, resp);
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}